package com.george.controller;

import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;

/**
 * <p>
 *  使用线程池创建线程
 * </p>
 *
 * @author GeorgeChan 2019/5/6 15:46
 * @version 1.0
 * @since jdk1.8
 */
@RestController
public class ThreadPoolExcutorController {
    public static void main(String[] args) throws InterruptedException {
        // 有界队列
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(5);
        // 放弃拒绝的任务并抛出异常
        RejectedExecutionHandler abortPolicyHandler = new ThreadPoolExecutor.AbortPolicy();
        RejectedExecutionHandler discardPolicyHandler = new ThreadPoolExecutor.DiscardPolicy();
        ThreadPoolExecutor threadPool =
                new ThreadPoolExecutor(5, 15, 10, TimeUnit.SECONDS, workQueue, discardPolicyHandler);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 40; i++) {
            System.out.println("当前i ===》 "+i);
            threadPool.execute(new MyTask());
            System.out.println("核心线程数" + threadPool.getCorePoolSize());
            System.out.println("最大线程数" + threadPool.getMaximumPoolSize());
            System.out.println("线程池数" + threadPool.getPoolSize());
            System.out.println("队列任务数" + threadPool.getQueue().size());
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        }

        System.out.println(System.currentTimeMillis()-start);
        threadPool.shutdown();
        if (threadPool.awaitTermination(6, TimeUnit.SECONDS)) {
            threadPool.shutdownNow();
        }
    }

    static class MyTask implements Runnable {

        @Override
        public void run() {
            try {
                Thread.currentThread().sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
